﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace Vs2010LoadTestPluginLib
{
    [DisplayName("Extract Regular Expression (better)")]
    [Description("Regular expression extraction rule, with more options")]
    public class BetterRegExExtractionRule : ExtractionRule 
    {
        [DisplayName("Html Decode")]
        [Description("if html decoding is needed")]
        [DefaultValue(true)]
        public bool HtmlDecode { get; set; }

        [DisplayName("Ignore Case")]
        [Description("whether to ignore case")]
        [DefaultValue(true)]
        public bool IgnoreCase { get; set; }
        //public bool Required { get; set; }

        [DisplayName("Header name to search")]
        [Description("If not empty search in this header value instead of the body. To search in a cookie use 'Set-Cookie'")]
        [DefaultValue("")]
        public string SearchHeaderName { get; set; }
        //Set-Cookie : GS=Site=frfr&Universe=sport&Login=patrizia

        [DisplayName("Regular Expression")]
        [Description("the regular expression")]
        public string RegularExpression { get; set; }

        [DisplayName("Match Group Name")]
        [Description("the group name to use as extracted value. If empty the Match Group Index is used.")]
        public string MatchGroupName { get; set; }

        [DisplayName("Match Group Index")]
        [Description("the match group index")]
        [DefaultValue(0)]
        public int MatchGroupIndex { get; set; }

        public override void Extract(object sender, ExtractionEventArgs e)
        {
            Regex r = new Regex(RegularExpression, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);

            var s = String.IsNullOrWhiteSpace(SearchHeaderName) ? e.Response.BodyString : e.Response.Headers[SearchHeaderName];
            if (String.IsNullOrWhiteSpace(s))
                return;

            var match = r.Match(s);
            if( match.Groups.Count != 0 )
            {
                string capture;
                if( !String.IsNullOrEmpty(MatchGroupName) )
                    capture = match.Groups[MatchGroupName].Value;
                else
                    capture = match.Groups[MatchGroupIndex].Value;

                e.WebTest.Context.Add(ContextParameterName, capture);
                e.Success = true;
            }
        }
    }
}
